import {
  DesktopOutlined,
  PieChartOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { useState } from "react";
import type { MenuProps } from "antd";
import { Menu } from "antd";

import { useNavigate, useLocation } from "react-router-dom";
type MenuItem = Required<MenuProps>["items"][number];
// function getItem(
//   label: React.ReactNode,
//   key: React.Key,
//   icon?: React.ReactNode,
//   children?: MenuItem[]
// ): MenuItem {
//   return {
//     key,
//     icon,
//     children,
//     label,
//   } as MenuItem;
// }

//展示的路由
const items: MenuItem[] = [
  {
    label: "飞车",
    key: "/home/feiche",
    icon: <PieChartOutlined></PieChartOutlined>,
  },
  {
    label: "联盟",
    key: "/home/lianmeng",
    icon: <DesktopOutlined></DesktopOutlined>,
  },
  {
    label: "电商三巨头",
    key: "jutou",
    icon: <UserOutlined></UserOutlined>,
    children: [
      {
        label: "淘宝",
        key: "/home/taobao",
      },
      {
        label: "京东",
        key: "/home/jingdong",
      },
      {
        label: "拼多多",
        key: "/home/pinduoduo",
      },
    ],
  },
  {
    label: "大厂",
    key: "dachang",
    icon: <UserOutlined></UserOutlined>,
    children: [
      {
        label: "百度",
        key: "/home/baidu",
      },
      {
        label: "腾讯",
        key: "/home/tenxun",
      },
    ],
  },
];
const Com = () => {
  const navigateTo = useNavigate(); //用于路由跳转
  const currentRoute = useLocation(); //刷新获取当前路径的path
  //在二级菜单中，刷新页面的时候，通过useLocation中的pathname遍历获取一级菜单中的pathname，然后赋值给openkeys用于刷新时显示二级菜单
  let pathObj: object | any = items.find((item: any): boolean | void => {
    if (item.children) {
      for (var i = 0; i < item.children.length; i++) {
        if (item.children[i].key == currentRoute.pathname) return true;
      }
    }
  });
  let pathName = pathObj?.key ? pathObj?.key : "";
  const [openKeys, setOpenKeys] = useState([pathName]);
  //menuItem 中的item点击时触发
  const titleClick = (e: { key: string }) => {
    navigateTo(e.key);
  };
  const openChange = (keys: string[]) => {
    setOpenKeys([keys[keys.length - 1]]);
  };
  return (
    <Menu
      openKeys={openKeys}
      onClick={titleClick}
      theme="dark"
      defaultSelectedKeys={[currentRoute.pathname]}
      mode="inline"
      items={items}
      onOpenChange={openChange}
    />
  );
};

export default Com;
